{% extends 'assets/base.html' %}
{% load static %}

{% block title %}智能推荐 - 固定资产管理系统{% endblock %}

{% block extra_css %}
<style>
    .recommendation-card {
        background: white;
        border-radius: 15px;
        padding: 25px;
        margin-bottom: 20px;
        box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        transition: all 0.3s;
        position: relative;
        overflow: hidden;
    }
    
    .recommendation-card:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 25px rgba(0,0,0,0.15);
    }
    
    .recommendation-card.unread {
        border-left: 5px solid #007bff;
    }
    
    .recommendation-header {
        display: flex;
        justify-content: between;
        align-items: flex-start;
        margin-bottom: 15px;
    }
    
    .recommendation-type {
        padding: 6px 12px;
        border-radius: 20px;
        font-size: 0.8em;
        font-weight: bold;
        margin-bottom: 10px;
        display: inline-block;
    }
    
    .type-maintenance { background: #e3f2fd; color: #1976d2; }
    .type-replacement { background: #fff3e0; color: #f57c00; }
    .type-optimization { background: #e8f5e8; color: #388e3c; }
    .type-allocation { background: #f3e5f5; color: #7b1fa2; }
    .type-procurement { background: #fce4ec; color: #c2185b; }
    
    .priority-urgent {
        background: linear-gradient(135deg, #ff5722 0%, #d32f2f 100%);
        color: white;
        padding: 4px 12px;
        border-radius: 15px;
        font-size: 0.75em;
        font-weight: bold;
        animation: pulse 2s infinite;
    }
    
    .priority-high {
        background: linear-gradient(135deg, #ff9800 0%, #f57c00 100%);
        color: white;
        padding: 4px 12px;
        border-radius: 15px;
        font-size: 0.75em;
        font-weight: bold;
    }
    
    .priority-medium {
        background: linear-gradient(135deg, #2196f3 0%, #1976d2 100%);
        color: white;
        padding: 4px 12px;
        border-radius: 15px;
        font-size: 0.75em;
        font-weight: bold;
    }
    
    .priority-low {
        background: linear-gradient(135deg, #4caf50 0%, #388e3c 100%);
        color: white;
        padding: 4px 12px;
        border-radius: 15px;
        font-size: 0.75em;
        font-weight: bold;
    }
    
    @keyframes pulse {
        0% { transform: scale(1); }
        50% { transform: scale(1.05); }
        100% { transform: scale(1); }
    }
    
    .confidence-score {
        background: #f8f9fa;
        border-radius: 10px;
        padding: 10px;
        text-align: center;
        margin-top: 15px;
    }
    
    .confidence-bar {
        height: 8px;
        background: #e9ecef;
        border-radius: 4px;
        overflow: hidden;
        margin-top: 5px;
    }
    
    .confidence-fill {
        height: 100%;
        background: linear-gradient(90deg, #ff4444, #ffaa00, #00aa00);
        transition: width 0.3s ease;
    }
    
    .recommendation-actions {
        display: flex;
        gap: 10px;
        margin-top: 20px;
    }
    
    .stats-card {
        background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        color: white;
        border-radius: 15px;
        padding: 25px;
        text-align: center;
        margin-bottom: 20px;
    }
    
    .filter-card {
        background: #f8f9fa;
        border-radius: 15px;
        padding: 20px;
        margin-bottom: 20px;
    }
    
    .asset-info {
        background: #f8f9fa;
        border-radius: 8px;
        padding: 12px;
        margin-top: 10px;
    }
    
    .recommendation-icon {
        font-size: 2.5rem;
        margin-bottom: 15px;
        opacity: 0.8;
    }
    
    .icon-maintenance { color: #2196f3; }
    .icon-replacement { color: #ff9800; }
    .icon-optimization { color: #4caf50; }
    .icon-allocation { color: #9c27b0; }
    .icon-procurement { color: #e91e63; }
</style>
{% endblock %}

{% block content %}
<div class="container-fluid">
    <div class="row">
        <div class="col-12">
            <div class="d-flex justify-content-between align-items-center mb-4">
                <h2><i class="fas fa-lightbulb"></i> 智能推荐</h2>
                <div>
                    <button class="btn btn-outline-primary" onclick="refreshRecommendations()">
                        <i class="fas fa-sync-alt"></i> 刷新推荐
                    </button>
                    <button class="btn btn-outline-secondary" onclick="markAllRead()">
                        <i class="fas fa-check-double"></i> 全部标记已读
                    </button>
                </div>
            </div>
            
            <!-- 统计信息 -->
            <div class="row mb-4">
                <div class="col-md-3">
                    <div class="stats-card">
                        <h3>{{ stats.total }}</h3>
                        <p class="mb-0">总推荐数</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <h3>{{ stats.unread }}</h3>
                        <p class="mb-0">未读推荐</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <h3>{{ stats.urgent }}</h3>
                        <p class="mb-0">紧急推荐</p>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stats-card">
                        <h3>{{ stats.accepted }}</h3>
                        <p class="mb-0">已采纳</p>
                    </div>
                </div>
            </div>
            
            <!-- 筛选条件 -->
            <div class="filter-card">
                <form method="get" class="row g-3">
                    <div class="col-md-3">
                        <label class="form-label">推荐类型</label>
                        <select name="type" class="form-select">
                            <option value="">全部类型</option>
                            <option value="maintenance" {% if type_filter == 'maintenance' %}selected{% endif %}>维修推荐</option>
                            <option value="replacement" {% if type_filter == 'replacement' %}selected{% endif %}>更换推荐</option>
                            <option value="optimization" {% if type_filter == 'optimization' %}selected{% endif %}>优化推荐</option>
                            <option value="allocation" {% if type_filter == 'allocation' %}selected{% endif %}>分配推荐</option>
                            <option value="procurement" {% if type_filter == 'procurement' %}selected{% endif %}>采购推荐</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">优先级</label>
                        <select name="priority" class="form-select">
                            <option value="">全部优先级</option>
                            <option value="urgent" {% if priority_filter == 'urgent' %}selected{% endif %}>紧急</option>
                            <option value="high" {% if priority_filter == 'high' %}selected{% endif %}>高</option>
                            <option value="medium" {% if priority_filter == 'medium' %}selected{% endif %}>中</option>
                            <option value="low" {% if priority_filter == 'low' %}selected{% endif %}>低</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">状态</label>
                        <select name="status" class="form-select">
                            <option value="">全部状态</option>
                            <option value="unread" {% if status_filter == 'unread' %}selected{% endif %}>未读</option>
                            <option value="read" {% if status_filter == 'read' %}selected{% endif %}>已读</option>
                            <option value="accepted" {% if status_filter == 'accepted' %}selected{% endif %}>已采纳</option>
                            <option value="dismissed" {% if status_filter == 'dismissed' %}selected{% endif %}>已忽略</option>
                        </select>
                    </div>
                    <div class="col-md-3">
                        <label class="form-label">&nbsp;</label>
                        <button type="submit" class="btn btn-primary d-block w-100">
                            <i class="fas fa-search"></i> 筛选
                        </button>
                    </div>
                </form>
            </div>
            
            <!-- 推荐列表 -->
            <div class="recommendations-container">
                {% for recommendation in page_obj %}
                <div class="recommendation-card {% if not recommendation.is_read %}unread{% endif %}" data-id="{{ recommendation.id }}">
                    <div class="recommendation-header">
                        <div class="flex-grow-1">
                            <div class="d-flex align-items-center justify-content-between">
                                <div>
                                    <span class="recommendation-type type-{{ recommendation.recommendation_type }}">
                                        {{ recommendation.get_recommendation_type_display }}
                                    </span>
                                    <span class="priority-{{ recommendation.priority }}">
                                        {{ recommendation.get_priority_display }}
                                    </span>
                                </div>
                                <div class="text-end">
                                    <small class="text-muted">
                                        {{ recommendation.created_at|date:"Y-m-d H:i" }}
                                    </small>
                                    {% if not recommendation.is_read %}
                                        <br><span class="badge bg-primary">新</span>
                                    {% endif %}
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <div class="col-md-8">
                            <h5 class="mb-3">
                                <i class="fas fa-{% if recommendation.recommendation_type == 'maintenance' %}tools icon-maintenance{% elif recommendation.recommendation_type == 'replacement' %}exchange-alt icon-replacement{% elif recommendation.recommendation_type == 'optimization' %}chart-line icon-optimization{% elif recommendation.recommendation_type == 'allocation' %}share-alt icon-allocation{% else %}shopping-cart icon-procurement{% endif %}"></i>
                                {{ recommendation.title }}
                            </h5>
                            
                            <p class="text-muted mb-3">{{ recommendation.description }}</p>
                            
                            {% if recommendation.asset %}
                            <div class="asset-info">
                                <h6><i class="fas fa-box"></i> 相关资产</h6>
                                <div class="row">
                                    <div class="col-md-6">
                                        <strong>{{ recommendation.asset.asset_number }}</strong><br>
                                        <small class="text-muted">{{ recommendation.asset.name }}</small>
                                    </div>
                                    <div class="col-md-6">
                                        <small class="text-muted">
                                            类别: {{ recommendation.asset.category.name }}<br>
                                            部门: {{ recommendation.asset.department.name|default:"未分配" }}
                                        </small>
                                    </div>
                                </div>
                            </div>
                            {% endif %}
                            
                            {% if recommendation.recommendation_data %}
                            <div class="mt-3">
                                <h6><i class="fas fa-info-circle"></i> 详细信息</h6>
                                <div class="row">
                                    {% for key, value in recommendation.recommendation_data.items %}
                                    <div class="col-md-6">
                                        <small><strong>{{ key }}:</strong> {{ value }}</small>
                                    </div>
                                    {% endfor %}
                                </div>
                            </div>
                            {% endif %}
                        </div>
                        
                        <div class="col-md-4">
                            <div class="confidence-score">
                                <h6><i class="fas fa-chart-bar"></i> 置信度</h6>
                                <h4 class="mb-2">{{ recommendation.confidence_score|floatformat:1 }}%</h4>
                                <div class="confidence-bar">
                                    <div class="confidence-fill" style="width: {{ recommendation.confidence_score }}%"></div>
                                </div>
                            </div>
                            
                            {% if recommendation.expires_at %}
                            <div class="mt-3 text-center">
                                <small class="text-warning">
                                    <i class="fas fa-clock"></i> 
                                    {% if recommendation.is_expired %}
                                        已过期
                                    {% else %}
                                        过期时间: {{ recommendation.expires_at|date:"m-d H:i" }}
                                    {% endif %}
                                </small>
                            </div>
                            {% endif %}
                        </div>
                    </div>
                    
                    <div class="recommendation-actions">
                        {% if not recommendation.is_accepted and not recommendation.is_dismissed %}
                            <button class="btn btn-success" onclick="acceptRecommendation({{ recommendation.id }})">
                                <i class="fas fa-check"></i> 采纳
                            </button>
                            <button class="btn btn-outline-secondary" onclick="dismissRecommendation({{ recommendation.id }})">
                                <i class="fas fa-times"></i> 忽略
                            </button>
                        {% endif %}
                        
                        {% if not recommendation.is_read %}
                            <button class="btn btn-outline-primary" onclick="markAsRead({{ recommendation.id }})">
                                <i class="fas fa-eye"></i> 标记已读
                            </button>
                        {% endif %}
                        
                        {% if recommendation.asset %}
                            <a href="{% url 'assets:asset_detail' recommendation.asset.id %}" class="btn btn-outline-info">
                                <i class="fas fa-external-link-alt"></i> 查看资产
                            </a>
                        {% endif %}
                        
                        <button class="btn btn-outline-danger" onclick="deleteRecommendation({{ recommendation.id }})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
                {% empty %}
                <div class="text-center text-muted py-5">
                    <i class="fas fa-lightbulb fa-3x mb-3"></i>
                    <h4>暂无智能推荐</h4>
                    <p>系统正在分析您的资产数据，稍后将为您提供个性化推荐</p>
                    <button class="btn btn-primary" onclick="refreshRecommendations()">
                        <i class="fas fa-sync-alt"></i> 立即生成推荐
                    </button>
                </div>
                {% endfor %}
            </div>
            
            <!-- 分页 -->
            {% if page_obj.has_other_pages %}
            <div class="d-flex justify-content-center mt-4">
                <nav>
                    <ul class="pagination">
                        {% if page_obj.has_previous %}
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.previous_page_number }}">上一页</a>
                            </li>
                        {% endif %}
                        
                        {% for num in page_obj.paginator.page_range %}
                            {% if page_obj.number == num %}
                                <li class="page-item active">
                                    <span class="page-link">{{ num }}</span>
                                </li>
                            {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                                <li class="page-item">
                                    <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ num }}">{{ num }}</a>
                                </li>
                            {% endif %}
                        {% endfor %}
                        
                        {% if page_obj.has_next %}
                            <li class="page-item">
                                <a class="page-link" href="?{% for key, value in request.GET.items %}{% if key != 'page' %}{{ key }}={{ value }}&{% endif %}{% endfor %}page={{ page_obj.next_page_number }}">下一页</a>
                            </li>
                        {% endif %}
                    </ul>
                </nav>
            </div>
            {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
// 采纳推荐
function acceptRecommendation(recommendationId) {
    if (!confirm('确定要采纳此推荐吗？')) {
        return;
    }
    
    $.ajax({
        url: `/assets/ai/recommendations/${recommendationId}/accept/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                showAlert('success', '推荐已采纳');
                updateRecommendationCard(recommendationId, 'accepted');
            } else {
                showAlert('error', response.message || '操作失败');
            }
        },
        error: function() {
            showAlert('error', '操作失败，请重试');
        }
    });
}

// 忽略推荐
function dismissRecommendation(recommendationId) {
    if (!confirm('确定要忽略此推荐吗？')) {
        return;
    }
    
    $.ajax({
        url: `/assets/ai/recommendations/${recommendationId}/dismiss/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                showAlert('success', '推荐已忽略');
                updateRecommendationCard(recommendationId, 'dismissed');
            } else {
                showAlert('error', response.message || '操作失败');
            }
        },
        error: function() {
            showAlert('error', '操作失败，请重试');
        }
    });
}

// 标记为已读
function markAsRead(recommendationId) {
    $.ajax({
        url: `/assets/ai/recommendations/${recommendationId}/read/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                const $card = $(`.recommendation-card[data-id="${recommendationId}"]`);
                $card.removeClass('unread');
                $card.find('.badge:contains("新")').remove();
                $card.find('button:contains("标记已读")').remove();
                
                showAlert('success', '已标记为已读');
            }
        }
    });
}

// 删除推荐
function deleteRecommendation(recommendationId) {
    if (!confirm('确定要删除此推荐吗？')) {
        return;
    }
    
    $.ajax({
        url: `/assets/ai/recommendations/${recommendationId}/delete/`,
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                $(`.recommendation-card[data-id="${recommendationId}"]`).fadeOut(300, function() {
                    $(this).remove();
                });
                showAlert('success', '推荐已删除');
            } else {
                showAlert('error', response.message || '删除失败');
            }
        },
        error: function() {
            showAlert('error', '删除失败，请重试');
        }
    });
}

// 全部标记已读
function markAllRead() {
    if (!confirm('确定要将所有推荐标记为已读吗？')) {
        return;
    }
    
    $.ajax({
        url: '/assets/ai/recommendations/mark-all-read/',
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                $('.recommendation-card.unread').removeClass('unread');
                $('.badge:contains("新")').remove();
                $('button:contains("标记已读")').remove();
                
                showAlert('success', `已标记 ${response.count} 条推荐为已读`);
            }
        }
    });
}

// 刷新推荐
function refreshRecommendations() {
    const $btn = $('button:contains("刷新推荐")');
    $btn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> 生成中...');
    
    $.ajax({
        url: '/assets/ai/recommendations/refresh/',
        method: 'POST',
        data: {
            'csrfmiddlewaretoken': '{{ csrf_token }}'
        },
        success: function(response) {
            if (response.success) {
                showAlert('success', '推荐已更新');
                setTimeout(function() {
                    location.reload();
                }, 1000);
            } else {
                showAlert('error', response.message || '刷新失败');
            }
        },
        error: function() {
            showAlert('error', '刷新失败，请重试');
        },
        complete: function() {
            $btn.prop('disabled', false).html('<i class="fas fa-sync-alt"></i> 刷新推荐');
        }
    });
}

// 更新推荐卡片状态
function updateRecommendationCard(recommendationId, status) {
    const $card = $(`.recommendation-card[data-id="${recommendationId}"]`);
    const $actions = $card.find('.recommendation-actions');
    
    if (status === 'accepted') {
        $actions.html('<span class="badge bg-success"><i class="fas fa-check"></i> 已采纳</span>');
    } else if (status === 'dismissed') {
        $actions.html('<span class="badge bg-secondary"><i class="fas fa-times"></i> 已忽略</span>');
    }
    
    $card.removeClass('unread');
}

// 显示提示信息
function showAlert(type, message) {
    const alertClass = type === 'success' ? 'alert-success' : 'alert-danger';
    const alertHtml = `
        <div class="alert ${alertClass} alert-dismissible fade show position-fixed" style="top: 20px; right: 20px; z-index: 9999;" role="alert">
            ${message}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    `;
    
    $('body').append(alertHtml);
    
    setTimeout(function() {
        $('.alert').alert('close');
    }, 3000);
}
</script>
{% endblock %}